package com.xh.demo.controller;

import com.xh.demo.commons.model.response.R;
import com.xh.demo.feign.ProductStockServiceFeign;
import com.xh.demo.model.request.OrderCreateRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @author wen
 * @apiNote OrderDetailController
 * @since 2021-12-10
 */
@Slf4j
@RestController
@RequestMapping("/core")
public class OrderCoreController {

    @Autowired
    private ProductStockServiceFeign productStockServiceFeign;

    @GetMapping("/v1/detail/{id}")
    public R<String> detail(@PathVariable("id") Long id) {
        return R.success(String.format("{\"orderId\":\"%s\",\"clientSecret\":\"1D2728858C7F36F4A8D04DDC4877B3E8\",\"path\":\"https://erp-open.hupun.com/api\",\"timeout\":30000}", id));
    }

    @GetMapping("/v2/detail/{id}")
    public R<String> detailV2(@PathVariable("id") Long id) throws InterruptedException {
        int random = ThreadLocalRandom.current().nextInt();
        if (random % 2 == 0) {
            Thread.sleep(5_000);
        }
        return R.success("order-detail-v2");
    }

    @GetMapping("/v3/detail/{id}")
    public R<String> detailV3(@PathVariable("id") Long id) {
        int random = ThreadLocalRandom.current().nextInt();
        if (random % 2 == 0) {
            throw new IllegalArgumentException("业务异常");
        }
        return R.success("order-detail-v3");
    }

    @PostMapping("/v1/order/{sku-id}")
    public R<String> create(@PathVariable("sku-id") Long skuId,
                            @RequestBody OrderCreateRequest request) {
        log.info("【订单创建-skuId】【{}】", request.getSkuId());
        R<String> result = productStockServiceFeign.reStock(skuId);
        if (result.getCode() == 200) {
            log.info("【商品库存服务】【{}】", result.getData());
        }
        return R.success("create-order-success");
    }

}
